package minicad;

import java.util.LinkedList;
import java.util.List;

import java.awt.*;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

class Model {
    Viewer viewer;
    List<Shape> shapeList = new LinkedList<>();
    Model(Viewer viewer){
        this.viewer = viewer;
    }
    void draw() {
        viewer.flush();
        for (Shape shape : shapeList) {
            shape.draw(viewer);
        }
    }
    void add(Shape s) {
        shapeList.add(s);
        draw();
    }
    void move(Shape s, int dx, int dy){
        s.move(dx, dy);
        draw();
    }
    void set_color(Shape s, Color c) {
        s.set_color(c);
        draw();
    }
    void scale(Shape s, double sc) {
        s.scale(sc);
        draw();
    }
    @SuppressWarnings("unchecked")
    void loadShapeList(String filename){
        try{
            ObjectInputStream in = 
                new ObjectInputStream(
                    new FileInputStream(filename));
            shapeList = (List<Shape>) in.readObject();
            draw();
            in.close();
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    void dumpShapeList(String filename){
        try{
            ObjectOutputStream out = 
                new ObjectOutputStream(
                    new FileOutputStream(filename));
            out.writeObject(shapeList);
            out.close();
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    Shape select(double x,double y) {
        // find with min dist; and threshold it to give the res
        double thre = 300;
        Shape res = null;
        int length = shapeList.size();
        if(length>0){
            res = shapeList.get(0);
            double min_dist = res.dist(x, y);
            for (Shape shape : shapeList) {
                double tmp = shape.dist(x, y);
                if(tmp<min_dist) {
                    min_dist = tmp;
                    res = shape;
                }
            }
            if(min_dist > thre) {
                res = null;
            }
        }
        return res;
    }
}